const Koa = require("koa");
// const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const mysql = require("mysql2/promise");
const router = require('./routes/index');

const app = new Koa();
// const router = new Router();
const port = 3001;

app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());
// app.use(bodyParser({ enableTypes: ['json', 'form', 'text', 'raw'] }));
// app.use(bodyParser({
//   enableTypes: ['json', 'form', 'text', 'raw'],
//   extendTypes: {
//     text: ['application/octet-stream'],
//   },
//   onerror: (err, ctx) => {
//     ctx.throw(422, 'Body parse error');
//   },
// }));
let users = [];
// 定义数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'student',
};
async function getUsersFromDatabase() {
  try {
    // 连接数据库
    const connection = await mysql.createConnection(dbConfig);

    // 查询stu_user表中的数据
    const [rows, fields] = await connection.execute("SELECT * FROM stu_user");

    // 将查询结果替换掉原来的users数组
    users = rows.map((row) => ({
      name: row.user_name,
      age: row.user_age,
      id: row.user_id,
    }));

    // 关闭数据库连接
    await connection.end();
  } catch (error) {
    console.error(error);
  }
}

getUsersFromDatabase();



router.get("/users", async (ctx) => {
  ctx.body = {
    users,
    code: 200,
    message: "获取成功啦",
  };
});

router.get("/users/:id", async (ctx) => {
  const userId = parseInt(ctx.params.id);
  const user = users.find((user) => user.id === userId);

  if (user) {
    ctx.body = user;
  } else {
    ctx.status = 404;
    ctx.body = { error: "出错啦" };
  }
});

router.post("/edit/:id", async (ctx) => {
  const userId = parseInt(ctx.params.id);
  const updatedUser = ctx.request.body;

  const userToUpdate = users.find((user) => user.id === userId);

  if (!userToUpdate) {
    ctx.status = 404;
    ctx.body = { error: "出错啦" };
    return;
  }

  const hasChanges = Object.keys(updatedUser).some(
    (key) => userToUpdate[key] !== updatedUser[key]
  );

  if (!hasChanges) {
    ctx.status = 400;
    ctx.body = { error: "未检测到任何更改" };
    return;
  }

  users = users.map((user) =>
    user.id === userId ? { ...user, ...updatedUser } : user
  );

  try {
    // 连接数据库
    const connection = await mysql.createConnection(dbConfig);

    // 更新数据库中对应的用户信息
    await connection.execute(
      "UPDATE stu_user SET user_name = ?, user_age = ? WHERE user_id = ?",
      [updatedUser.name, updatedUser.age, userId]
    );

    // 关闭数据库连接
    await connection.end();
  } catch (error) {
    console.error(error);
    ctx.status = 500;
    ctx.body = { error: "数据库操作失败" };
    return;
  }

  ctx.body = { message: "用户更新成功" };
});

router.delete("/delete/:id", async (ctx) => {
  const userId = parseInt(ctx.params.id);
  const userToDelete = users.find((user) => user.id === userId);

  if (!userToDelete) {
    ctx.status = 404;
    ctx.body = { error: "用户不存在" };
    return;
  }

  try {
    // 连接数据库
    const connection = await mysql.createConnection(dbConfig);

    // 从数据库中删除对应的用户信息
    await connection.execute("DELETE FROM stu_user WHERE user_id = ?", [
      userId,
    ]);

    // 关闭数据库连接
    await connection.end();
  } catch (error) {
    console.error(error);
    ctx.status = 500;
    ctx.body = { error: "数据库操作失败" };
    return;
  }

  users = users.filter((user) => user.id !== userId);
  ctx.body = { message: "删除成功" };
});

async function getUserInfoFromDatabase(userId) {
  try {
    const connection = await mysql.createConnection(dbConfig);

    const [rows, fields] = await connection.execute(
      "SELECT * FROM user_info WHERE id = ?",
      [userId]
    );

    await connection.end();

    return rows[0];
  } catch (error) {
    console.error(error);
    throw error;
  }
}

router.get("/userInfo/:id", async (ctx) => {
  const userId = parseInt(ctx.params.id);

  try {
    const userInfo = await getUserInfoFromDatabase(userId);

    if (userInfo) {
      ctx.body = {
        avatar: userInfo.avatar_url,
        name: userInfo.name,
        website: userInfo.website,
        age: userInfo.age,
        country: userInfo.country,
        profession: userInfo.profession,
        hobbies: userInfo.hobbies.split(","),
        neckname: userInfo.neckname,
      };
    } else {
      ctx.status = 404;
      ctx.body = { error: "用户不存在" };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: "数据库操作失败" };
  }
});




app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port} 端口`);
});
